<?php

function ListDir($dir) 
{
	$handle	  =   OpenDir($dir);
	$List_Dir	  =   Array();
	$List_File    =   Array();
	$List		  =   Array();
	while( $file = ReadDir( $handle) )
	{
		$type = filetype("$dir/$file");
		if( $type == 'dir' ) {
			if($file != "." ) Array_Push($List_Dir,$file);
		}
		else if($type == 'file'){
			Array_Push($List_File,$file);
		}
	}
	CloseDir( $handle );
	Array_Push($List,$List_Dir,$List_File);
	
	Return $List;
}



function dirJson($dir, $base='', $showUp=true) 
{
	$Detail = array(
		'dir' => $base,
		'files'=> array()
	);
	$List = ListDir($dir);

	$len = count($List[0]);
	for($i=0; $i<$len; $i++)
	{
		$name = $List[0][$i];
		if($name=='..' && !$showUp)
			continue;
		$Detail['files'][] = Array(
			'name' => $name,
			'type' => 'd'
		);
	}

	$len = count($List[1]);
	for($i=0; $i<$len; $i++)
	{
		$fileName = $List[1][$i];
		$Detail['files'][] = Array(
			'name' => $fileName,
			'type' => 'f'
		);
	}
			
	return Json_Encode($Detail);
}

function checkUTF8($fileContent) 
{
	$isUTF = ($fileContent === mb_convert_encoding(mb_convert_encoding($fileContent, "UTF-32", "UTF-8"), "UTF-8", "UTF-32"));
	return ($isUTF ? true : false) ;
}

function GetFile($file)
{
	$fileContent = "";
	if( $file )
	{
		$handle = Fopen($file,"rb");
		while( !Feof($handle))
		{
			$fileContent = $fileContent . FGets($handle);
		}
		fclose($handle);
		if( !checkUTF8($fileContent) )   $fileContent = iconv( "GB2312" , "UTF-8" , $fileContent ); 
		return $fileContent;
	}
}

function writeFile($file,$content) 
{
	if ( is_writable($file) )
	{
		$handle   = fopen($file,"w");
		$flocked  = flock($handle,LOCK_EX);  // Using "2" instead "LOCK_EX" in PHP4.01 or brfore please.
		if ( !fwrite( $handle, $content ) && $flocked )
		{ 
			flock($handle,LOCK_UN); // Using "3" instead "LOCK_UN" in PHP4.01 or brfore please.
			fclose($handle);
			return 1;
		}else{
			flock($handle,LOCK_UN); // Using "3" instead "LOCK_UN" in PHP4.01 or brfore please.
			fclose($handle);
			return 0;
		}
	}else{
		return 2;
	}
}

function createNewFile($fileName,$filePath)
{
	$file = $filePath . '/' .$fileName;
	if( file_exists( $file ) ) return 0;
	$handle = fopen( $file , "w+" );
	
	fwrite( $handle , "" );
	fclose( $handle );
	return 1;
}


?>
